package com.zhiqianbao.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.creditx.xbehavior.sdk.ActionName;
import com.creditx.xbehavior.sdk.CreditXAgent;
import com.creditx.xbehavior.sdk.PageName;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.ApplyCouponInfo;
import com.zhiqianbao.entity.ApplyStateInfo;
import com.zhiqianbao.entity.Checklines;
import com.zhiqianbao.entity.CreditRating;
import com.zhiqianbao.entity.PhoneContact;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserPhoneCheck;
import com.zhiqianbao.listener.MyLocationListener;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.LoanUtils;
import com.zhiqianbao.utils.PermissionDialog;
import com.zhiqianbao.utils.PermissionsManager;
import com.zhiqianbao.utils.T;
import com.zhiqianbao.utils.WorthPurseUtil;
import com.zhiqianbao.view.LongClickButton;
import com.zhiqianbao.view.WheelView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;


/**
 * Created by liang on 2016/1/27.
 * 借款模块页面
 */
public class ApplyLoanFragment extends LazyLoadFragment implements View.OnClickListener{
    private static final int REQUEST_CODE = 2;
    public static final int DATA_FAILD=0x122;
    public static final int CURRENTQUOTA=0x123;
    public static final int CHECKNO=0x124;
    /**
     * 日期选择车轮控件
     */
    WheelView wva;
    /**
     * 金钱减按钮
     */
    LongClickButton buttonMoneyMinus;
    private int data_state;
    /**
     * 金钱加按钮
     */
    LongClickButton buttonMoneyAdd;
    /**
     * 金钱显示
     */
    TextView howmoneyNum;
    private View view;
    private String data;
    /**
     * 最小金额显示
     */
    TextView moneyMinContent;
    /**
     * 最大金额显示
     */
    TextView moneyMaxContent;

    /**
     * 下一步
     */
    Button buttonApplyMoney;
    ImageView urgent_coupon_checkbox;
    TextView coupon_urgent_tv;
    int currentMonth = 1;
    int currentMoney = 500;
    TextView textViewReturnMoneyContent;
    /**
     * 异步查询数据库对象
     */
    private AsyncQueryHandler asyncQueryHandler;
    Gson gson = new Gson();

    private List<PhoneContact> phoneContactList = new ArrayList<>();

    private Map<Integer, PhoneContact> contactIdMap = null;
    private ScrollView srcollview_container_item1;

    private boolean isUpload = false;
    SharedPreferanceUtils sharedPreferanceUtils;
    private String couponId = "";
    private String contractNum = "";
    public int checkCoupId = -1;//判断是否有优惠券，只有0与1状态可以切换，1有优惠券，0未有优惠券
    Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            howmoneyNum.setText(currentMoney + "");
            createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
        }
    };

    Handler userPhoneCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    try {
                        Result<UserPhoneCheck> data = (Result<UserPhoneCheck>) msg.obj;
                        if (data == null) {
                            showShortToast1("抱歉，请求失败，请重新请求");
                            return;
                        }
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            UserPhoneCheck userPhoneCheck = data.getData();
                            //还没有进行手机验证，跳转到输入手机号信息的页面
                            if (userPhoneCheck == null) {
                                Intent bindPhoneIntent = new Intent(getActivity(), ProcessActivity.class);
                                startActivity(bindPhoneIntent);
                                return;
                            }
                            //已经验证，但是需要进行下一步处理，跳转到下一步处理页面
                            String status = userPhoneCheck.getStatus() != null ?
                                    userPhoneCheck.getStatus() : "";
                            if (Constants.CALL_DETAILS_STATUS_DONE.equals(status)) {
                                intentApplyVerify();
                            }
                            else if(Constants.CALL_DETAILS_STATUS_TIMEOUT.equals(status)){
                                phoneTimeOutDialog();
                            }
                            else{
                                Intent bindPhoneIntent = new Intent(getActivity(), ProcessActivity.class);
                                startActivity(bindPhoneIntent);
                            }
                            closeWaitDialog();
                        }
                        else{
                            showShortToast1(data.getMsg());
                        }
                    }
                    catch (JsonIOException exception){
                        showShortToast1("抱歉，请求失败，请重新请求");
                    }
                    catch (NullPointerException exception){
                        showShortToast1("抱歉，请求失败，请重新请求");
                    }
                    break;
                case 0:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }


        }
    };
    Handler applyhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Result<ApplyStateInfo> data = (Result<ApplyStateInfo>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals("9")) {
                            Constants.LOGIN_USER = null;
                            //清空用户信息
                            if(getActivity()!=null) {
                                Intent intent = new Intent(getActivity(),
                                        WorthPurseUtil.getZhiddActivity().getClass());
                                getActivity().startActivity(intent);
                                showShortToast1("您的账号在其他设备登录,请重新登录");
                                getActivity().finish();
                            }
                        } else if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            ApplyStateInfo dataBean = data.getData();
                            if (dataBean != null) {
                                String lianlianState = dataBean.getLianlianState();
                                String applyState = dataBean.getApplyState();
                                String overdueStates = dataBean.getOverdueStatus();
                                if (applyState.length()>6) {
                                    contractNum = applyState;
                                    //1是已签约，其他未签约
                                    if (lianlianState.equals("1")) {
                                        //1是超过了30天
                                        if (overdueStates.equals("1")) {
                                            startActivity(new Intent(getActivity(), VerificationPhoneActivity.class));
                                            closeWaitDialog();
                                        } else {
                                            phoneCheck();
                                        }
                                    } else {
                                        startActivity(new Intent(getActivity(), BankCardInfoActivity.class));
                                        closeWaitDialog();
                                    }
                                } else if (applyState.equals("2")) {
                                    showShortToast1("您的账号处于锁定状态，请等待系统解锁后再次申请");
                                    closeWaitDialog();
                                } else {
                                    showShortToast1("您已经存在正在处理的借款申请");
                                    closeWaitDialog();
                                }
                            } else {
                                showShortToast1("抱歉，请求数据失败，请重试！");
                                closeWaitDialog();
                            }
                        } else {
                            showShortToast1(data.getMsg() != null ? data.getMsg() : "");
                        }
                    }
                    break;
            }

            closeWaitDialog();
        }
    };

    /**
     * 判断是否可以进入借款详情页面
     */
    public void intentApplyVerify(){
            if (Constants.BD_LOCATION == null) {
                showShortToast1("请开启定位权限，重新启动应用。");
                closeWaitDialog();
                return;
            }
            else{
                //如果此时关闭了系统获取位置权限，则需要通过当前位置是否为空判断
                if(TextUtils.isEmpty(Constants.BD_LOCATION.getAddrStr())){
                    showShortToast1("请开启定位权限，重新启动应用。");
                    closeWaitDialog();
                    return;
                }
            }

            //判断用户是否开启通讯录权限
            if (!checkContactsPermission()) {
                showShortToast1("请开启通讯录权限，否则影响审核结果！");
                closeWaitDialog();
                return;
            }
            FileUtils.deleteCache("apply.txt");
            if (checkCoupId == 0) {
                expressCouponDialog();
            } else {
                exterApplyVerify(couponId, contractNum);
            }
    }
    /**
     * 信用表
     */
    CreditRating creditRating;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_loan_apply_tab, null);
        srcollview_container_item1 = (ScrollView) view.findViewById(R.id.srcollview_container_item1);
        sharedPreferanceUtils = new SharedPreferanceUtils(getActivity());
        initView(view);

        moneyMaxContent.setText("5000");
        updateSelected();
        checkPermission_v4(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_SETTINGS, Manifest.permission.ACCESS_COARSE_LOCATION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getActivity())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                        Uri.parse("package:" + getActivity().getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, REQUEST_CODE);
            } else {

            }
        }
        return view;
    }


    private PermissionDialog permissionDialog;

    private boolean checkPermission_v4(final String... permission) {
        if (perManager == null)
            perManager = new PermissionsManager(getActivity(), new PermissionsManager.PermissionListener() {
                // 添加权限请求返回监听器并内置了一个二次提示框
                @Override
                public void getRequestPermissionCallBack(String[] permissions, boolean isAgree) {
                    // 权限没有全部获取
                    if (!isAgree) {
                        final String[] p = permissions;
                        // 向用户弹出一个提示框,包含确定和取消两个按钮
                        if (permissionDialog == null)
                            permissionDialog = new PermissionDialog(getActivity(), new PermissionDialog.PermissionCheckListener() {

                                @Override
                                public void userChoosed(boolean isChooseOk) {
                                    if (isChooseOk) {// 点击确定
                                        // 先检查一下有没有完全禁止，有的话那就拜拜了您那~~ 让系统安全应用去处理吧
                                        checkShouldShowPermission(p);
                                        // 没有就再次检查指导结束
                                        checkPermission_v4(permission);
                                    } else {// 点击取消
                                        // 关闭页面
                                    }
                                }
                            });
                        permissionDialog.show();
                    }
                }
            });
        // 检查是否已有权限
        return perManager.checkPermission(permission);
    }

    /**
     * 检查是否可以显示权限授予对话框
     *
     * @param permissions
     * @author Wall
     */
    public void checkShouldShowPermission(String[] permissions) {
        if (perManager != null) {
            // 检查是否已被禁止
            boolean isNeedShow = perManager.checkShouldShowPermission(permissions);
            if (isNeedShow) {
                T.getInstanse(getActivity()).showLong(R.string.exception_nopermission);
            }
        }
    }

    private PermissionsManager perManager;

    public boolean checkPermission_v4(final PermissionsManager.PermissionListener listener, final String... permission) {
        if (perManager == null)
            perManager = new PermissionsManager(getActivity(), listener);
        return perManager.checkPermission(permission);
    }


    private void initData() {
        //可提现额度
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/auth/currentQuota",
                        mapParams, getActivity());
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILD;
                } else {
                    message.what = CURRENTQUOTA;
                    Checklines data =gson.fromJson(result, Checklines.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 判断是否有WRITE_SETTINGS权限
                if (Settings.System.canWrite(getActivity())) {

                }
            }
        }
    }

    private void initView(final View view) {
        try {
            // 取出用户的额度 和 信用等级
            List<CreditRating> creditRatings = CreditRating.find(CreditRating.class, null, new String[]{});
            if (creditRatings.isEmpty()) {
                //没有登录 获取默认数据
                creditRating = new CreditRating();
                creditRating.setYearRate(0.24);
                creditRating.setManageFee(BigDecimal.valueOf(40));
                creditRating.setCreditLine(5000);
                creditRating.setTermLine(6);
            } else {
                creditRating = creditRatings.get(0);
            }
            //初始化各个控件
            urgent_coupon_checkbox = (ImageView) view.findViewById(R.id.urgent_coupon_checkbox);
            coupon_urgent_tv = (TextView) view.findViewById(R.id.coupon_urgent_tv);
            buttonMoneyMinus = (LongClickButton) view.findViewById(R.id.button_moneyMinus);
            buttonMoneyAdd = (LongClickButton) view.findViewById(R.id.button_moneyAdd);
            howmoneyNum = (TextView) view.findViewById(R.id.howmoney_num);
            moneyMinContent = (TextView) view.findViewById(R.id.money_min_content);
            moneyMaxContent = (TextView) view.findViewById(R.id.money_max_content);
            textViewReturnMoneyContent = (TextView) view.findViewById(R.id.textView_returnMoney_content);
            buttonApplyMoney = (Button) view.findViewById(R.id.button_applyMoney);

            moneyMinContent.setText("500");
//            moneyMaxContent.setText(creditRating.getCreditLine() + "");
            howmoneyNum.setText("500");

            buttonApplyMoney.setOnClickListener(this);
            buttonMoneyAdd.setOnClickListener(this);
            urgent_coupon_checkbox.setOnClickListener(this);
            coupon_urgent_tv.setOnClickListener(this);
            buttonMoneyMinus.setOnClickListener(this);

            //初始化借款信息
            createApplyMoneyInfo(currentMoney, currentMonth, creditRating);

            wva = (WheelView) view.findViewById(R.id.howtimes_num);
            wva.setOffset(1);
            List<String> months = new ArrayList<>();
            for (int i = 1; i <= creditRating.getTermLine(); i++) {
                months.add(i + "");
            }
            wva.setItems(months);
            setChangeMoney();
            /**
             * 防止scroview衝突
             */
            srcollview_container_item1.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    view.findViewById(R.id.howtimes_num).getParent().requestDisallowInterceptTouchEvent(false);
                    return false;
                }
            });
            wva.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    return false;
                }
            });
            wva.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                @Override
                public void onSelected(int selectedIndex, String item) {
                    currentMonth = Integer.valueOf(item);
                    String appData = sharedPreferanceUtils.getAppData();
                    if (appData.equals("0")) {
//                    currentMonth = 0;
                        createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
                    } else {
                        createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
                    }

                }
            });

        } catch (Exception e) {

        }

    }

    /**
     * 主要针对长点击添加或减少借款数目变化
     */
    public void setChangeMoney() {
        buttonMoneyAdd.setLongClickRepeatListener(new LongClickButton.LongClickRepeatListener() {
            @Override
            public void repeatAction() {
                currentMoney += 100;
                currentMoney = currentMoney > 5000 ? 5000 : currentMoney;
                howmoneyNum.setText(currentMoney + "");
                createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
            }
        });

        buttonMoneyMinus.setLongClickRepeatListener(new LongClickButton.LongClickRepeatListener() {
            @Override
            public void repeatAction() {
                currentMoney -= 100;
                currentMoney = currentMoney > 500 ? currentMoney : 500;
                howmoneyNum.setText(currentMoney + "");
                createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if(R.id.button_moneyMinus==v.getId()) {
            currentMoney -= 100;
            currentMoney = currentMoney < 500 ? 500 : currentMoney;
            howmoneyNum.setText(currentMoney + "");
            createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
        }
        else if(R.id.button_moneyAdd==v.getId()) {
                currentMoney += 100;
                currentMoney = currentMoney > 5000 ? 5000 : currentMoney;
                howmoneyNum.setText(currentMoney + "");
                createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
        }
        else if(R.id.button_applyMoney==v.getId()) {
            if (Constants.LOGIN_USER == null) {
                Intent loginIntent = new Intent(getActivity(),
                        WorthPurseUtil.getZhiddActivity().getClass());
                startActivity(loginIntent);
                getActivity().finish();
            } else {
                CreditXAgent.onClick(ActionName.Click.LOAN_INDEX_LOAN_CLICKED);
                subsitApply();
            }
        }
        else if(R.id.urgent_coupon_checkbox==v.getId()||(R.id.coupon_urgent_tv==v.getId())) {
            if (Constants.LOGIN_USER != null) {
                if (checkCoupId == 1) {
                    checkCoupId = 0;
                    urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
                } else if (checkCoupId == 0) {
                    checkCoupId = 1;
                    urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_select);
                } else {
                    showShortToast1("您目前无可用加急券!");
                }
            } else {
                couponId = "";
                startActivity(new Intent(getMyActivity(),
                        WorthPurseUtil.getZhiddActivity().getClass()));
                getMyActivity().finish();
            }
        }
    }
    /**
     * 借款信息显示
     *
     * @param money
     * @param time
     */
    private void createApplyMoneyInfo(Integer money, Integer time, CreditRating creditRating) {


//            String appData = sharedPreferanceUtils.getAppData();
//        if(Constants.LOGIN_USER == null && data_state == 0){
//            money = 500;
//        }
//        if (data_state == 0 && Constants.LOGIN_USER !=null) {o
//            money = 0;
//        } else {
        money = LoanUtils.averageCapitalPlusInterest(BigDecimal.valueOf(money), BigDecimal.valueOf(creditRating.getYearRate()), time, creditRating.getManageFee()).intValue();
//        }

        String str1 = "借款到账日后30天还款，每期还款";
        String str2 = "元，共";
        String str3 = "期";

        String str = str1 + money.toString() + str2 + time.toString() + str3;

        int l1 = str1.length();
        int l2 = str2.length();
        int l3 = str3.length();
        int lm = money.toString().length();
        int lt = time.toString().length();

        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
        ForegroundColorSpan moneySpan = new ForegroundColorSpan(getResources().getColor(R.color.numt_tv_color));
        ForegroundColorSpan timeSpan = new ForegroundColorSpan(getResources().getColor(R.color.tab_account_listview_item_green));
        ForegroundColorSpan blackSpan = new ForegroundColorSpan(Color.BLACK);
        try {
            SpannableStringBuilder builder = new SpannableStringBuilder("*" + str);
            builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(moneySpan, l1 + 1, l1 + 1 + lm, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            builder.setSpan(timeSpan, l1 + 1 + lm + l2, l1 + 1 + lm + l2 + lt, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            textViewReturnMoneyContent.setText(builder);
        } catch (Exception e) {

        }

    }

    boolean isUserVisible = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            Log.i(getClass().getSimpleName(), "可见状态");
            updateSelected();
        } else {
            Log.i(getClass().getSimpleName(), "不可见状态");
        }
        isUserVisible = isVisibleToUser;
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_loan_apply_tab;

    }

    @Override
    protected void lazyLoad() {
      //  initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        CreditXAgent.onEnteringPage(PageName.LOAN_INDEX);
        ApplyTabHostActivity tabHostActivity = (ApplyTabHostActivity) getActivity();
        if (Constants.LOGIN_USER != null) {
            if (isUserVisible) {
              //  initData();
            checkExpressCoupon();
            }
        } else {
            couponId = "";
            checkCoupId = -1;
            coupon_urgent_tv.setTextColor(Color.parseColor("#ff535353"));
            urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        CreditXAgent.onLeavingPage(PageName.LOAN_INDEX);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (waitDialog != null)
            waitDialog.dismiss();
    }

    public void updateSelected() {
        // 取出用户的额度 和 信用等级
        List<CreditRating> creditRatings = CreditRating.find(CreditRating.class, null, new String[]{});
        if (Constants.LOGIN_USER != null && !creditRatings.isEmpty()) {
            creditRating = creditRatings.get(0);
            if (wva != null) {
                //日期选择
                List<String> months = new ArrayList<>();
                for (int i = 1; i <= creditRating.getTermLine(); i++) {
                    months.add(i + "");
                }
                if (!wva.isEmpty()) {
                    String selectedItem = wva.getSeletedItem();
                    wva.setItems(months);
                    wva.setSelectedItem(Integer.parseInt(selectedItem));
                }
                //金钱选择
//                    moneyMinContent.setText("500");
                //就是这里
//                    moneyMaxContent.setText(creditRating.getCreditLine() + "");
                currentMoney = currentMoney <= creditRating.getCreditLine() ? currentMoney : creditRating.getCreditLine();
//                    howmoneyNum.setText(currentMoney + "");
            }
        }
        displayCache(creditRating);
    }

    public void displayCache(CreditRating creditRating) {
        try {
            Map<String, String> data = FileUtils.getUserInfo("apply.txt");
            if (data != null) {
                String money = data.get("value1");
                String month = data.get("value2");
                if (!StringUtils.isBlank(money) && !StringUtils.isBlank(month)) {

                    currentMoney = Integer.parseInt(money);
                    currentMonth = Integer.parseInt(month);
                    wva.setSelectedItem(Integer.parseInt(month));
                    wva.setSeletion(Integer.parseInt(month) - 1);
                    if (howmoneyNum.getText().toString().equals("0") && data_state > 0)
                        howmoneyNum.setText("500");
                    if (currentMonth > 0) {
                        if (Integer.parseInt(howmoneyNum.getText().toString()) != currentMoney)
                            currentMoney = Integer.parseInt(howmoneyNum.getText().toString());
                        createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
                    }
                } else {
                    try {
                        if (howmoneyNum.getText().toString().equals("0") && data_state > 0)
                            howmoneyNum.setText("500");
                        if (currentMonth > 0) {
                            if (Integer.parseInt(howmoneyNum.getText().toString()) != currentMoney)
                                currentMoney = Integer.parseInt(howmoneyNum.getText().toString());
                            createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
                        }
                    } catch (Exception e) {

                    }

                }
            } else {
                if (howmoneyNum.getText().toString().equals("0") && data_state > 0)
                    howmoneyNum.setText("500");
                if (currentMonth > 0) {
                    if (Integer.parseInt(howmoneyNum.getText().toString()) != currentMoney)
                        currentMoney = Integer.parseInt(howmoneyNum.getText().toString());
                    createApplyMoneyInfo(currentMoney, currentMonth, creditRating);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启定位服务
     */
    private void location() {
        Constants.LOCATION_LISTENER = new MyLocationListener();
        if(getActivity()==null){
            return;
        }
        Constants.LOCATION_CLIENT = new LocationClient(getActivity().getApplicationContext());
        Constants.LOCATION_CLIENT.registerLocationListener(Constants.LOCATION_LISTENER);
        Constants.LOCATION_CLIENT.setLocOption(initLocation());
        if (!Constants.LOCATION_CLIENT.isStarted()) {
            Constants.LOCATION_CLIENT.start();
        }
    }

    private LocationClientOption initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(true);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        return option;
    }

    private boolean checkContactsPermission() {
        phoneContactList.clear();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;//联系人Uri
        // 查询的字段
        String[] projection = {
                ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.DATA1,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.LAST_TIME_CONTACTED,
                ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED
        };
        // 按照sort_key升序查詢
        try {
            Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, "sort_key COLLATE LOCALIZED asc");
            if (cursor != null) {
                PhoneContact.deleteAll(PhoneContact.class);
                contactIdMap = new HashMap<>();
                cursor.moveToFirst();//游标移动到第一页
                for (int i = 0; i < cursor.getCount(); i++) {
                    cursor.moveToPosition(i);
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                    int contactId = cursor.getInt(3);
                    Long lastTimeContacted = cursor.getLong(4);
                    Long timesContacted = cursor.getLong(5);
                    if (!contactIdMap.containsKey(contactId)) {
                        PhoneContact phoneContact = new PhoneContact();
                        phoneContact.setContactId(contactId);
                        phoneContact.setDesplayName(name);
                        phoneContact.setPhoneNum(number);
                        phoneContact.setLastTimeContacted(lastTimeContacted);
                        phoneContact.setTimesContacted(timesContacted);
                        phoneContactList.add(phoneContact);
                        contactIdMap.put(contactId, phoneContact);
                    }
                }
            }
        } catch (Exception e) {

        }


        if (phoneContactList.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 是否有加急券提示弹出框
     */
    public void expressCouponDialog() {
        final AlertDialog builder = new AlertDialog.Builder(getActivity(), R.style.Dialog).create();
        builder.show();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_express_coupon_layout, null);
        builder.getWindow().setContentView(view);
        builder.setCanceledOnTouchOutside(false);
        TextView repay_money = (TextView) view.findViewById(R.id.repay_money);
        Button button = (Button) view.findViewById(R.id.positiveButton);
        Button cacelButton = (Button) view.findViewById(R.id.cacelButton);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkCoupId = 1;
                urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_select);
                exterApplyVerify(couponId, contractNum);
                builder.dismiss();
            }
        });

        cacelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkCoupId = 0;
                urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
                exterApplyVerify("", contractNum);
                builder.dismiss();
            }
        });
    }

    /**
     * 手机号有效期超过30天有效期提示弹出框
     */
    public void phoneTimeOutDialog() {
        final AlertDialog builder = new AlertDialog.Builder(getActivity(), R.style.Dialog).create();
        builder.show();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_express_coupon_layout, null);
        builder.getWindow().setContentView(view);
        builder.setCanceledOnTouchOutside(false);
        TextView repay_money = (TextView) view.findViewById(R.id.repay_money);
        Button button = (Button) view.findViewById(R.id.positiveButton);
        Button cacelButton = (Button) view.findViewById(R.id.cacelButton);
        repay_money.setText("请先通过运营商认证后，再进行借款！");
        button.setText("确定");
        cacelButton.setText("取消");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent bindPhoneIntent = new Intent(getActivity(), ProcessActivity.class);
                startActivity(bindPhoneIntent);
                builder.dismiss();
            }
        });

        cacelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
    }

    /**
     * 进入借款详情页面
     */
    public void exterApplyVerify(String couponId, String contractNum) {
        Intent verifyIntent = new Intent(getActivity(), ApplyVerifyActivity.class);
        verifyIntent.putExtra("capital", currentMoney);
        verifyIntent.putExtra("termLine", currentMonth);
        verifyIntent.putExtra("contractNum", contractNum);
        final List<PhoneContact> phoneContacts = phoneContactList;
        String phoneJosn = gson.toJson(phoneContacts);
        verifyIntent.putExtra("phoneJosn", phoneJosn);
        verifyIntent.putExtra("couponId", couponId);
        startActivityForResult(verifyIntent, 1);
    }

    public void phoneCheck() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message phoneCheckMessage = new Message();
                Map<String, String> params = new HashMap<>();
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("phone", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone()+ "" : "");

                //1.0.7
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/checkNew", params, getActivity());
                if(!TextUtils.isEmpty(result)){
                    Log.i("ApplyLoanFragment",""+result);
                }
                else{
                    Log.i("ApplyLoanFragment","这是空");
                }
                if (StringUtils.isBlank(result)) {
                    phoneCheckMessage.what = 0;
                } else {
                    phoneCheckMessage.what = 1;
                    Result<UserPhoneCheck> data = Result.fromJson(result, UserPhoneCheck.class);
                    phoneCheckMessage.obj = data;
                }
                userPhoneCheckHandler.sendMessage(phoneCheckMessage);
            }
        }).start();
    }

    public void checkLoanApply() {
        if (Constants.LOGIN_USER == null) {
            Intent loginIntent = new Intent(getActivity(),
                    WorthPurseUtil.getZhiddActivity().getClass());
            startActivity(loginIntent);
            getActivity().finish();
        }else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    Map<String, String> params = new HashMap<>();
                    params.put("token", Constants.LOGIN_USER.getToken() != null ? Constants.LOGIN_USER.getToken() + "" : "");
                    params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/loan/checkLoanState", params, getActivity());
                    if (StringUtils.isBlank(result)) {
                        message.what = 0;

                    } else {
                        message.what = 1;
                        Result<ApplyStateInfo> data = Result.fromJson(result, ApplyStateInfo.class);
                        message.obj = data;
                    }
                    applyhandler.sendMessage(message);
                }
            }).start();
        }
    }


    public void checkExpressCoupon() {
        //获取当前系统时间
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/checkNoAnnouncementNew",
                        mapParams, getActivity());
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILD;
                } else {
                    message.what = CHECKNO;
                    ApplyCouponInfo data =gson.fromJson(result, ApplyCouponInfo.class);
                     message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();

    }

    public void subsitApply() {
        String telecon = sharedPreferanceUtils.getTelecon();
        String emergency = sharedPreferanceUtils.getEmergency();
        String jobState = sharedPreferanceUtils.getJobState();
        String cardstarte = sharedPreferanceUtils.getidCardState();
        if (telecon.equals("1") && emergency.equals("1") && jobState.equals("1") && cardstarte.equals("1")) {
            try {
                FileUtils.saveToRom(getActivity(), currentMoney + "", currentMonth + "", "apply.txt");
            } catch (Exception e) {
                e.printStackTrace();
            }
            location();
            showWaitDialog();
            //判断用户 是否进行手机号验证(需要测试)
            checkLoanApply();
        } else  {
            showAlertMsgDialog("信息资料认证未完成", "确认", "取消");
        }
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FAILD:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case CURRENTQUOTA:
                    Checklines response = (Checklines) msg.obj;
                    if (response != null) {
                        if (response.getCode().equals("0")) {
                            String a = response.getData();

                            if (!TextUtils.isEmpty(a)) {
                                try {
                                    data_state = Integer.parseInt(a.split("\\.")[0]);
                                    sharedPreferanceUtils.setAppData(data_state + "");
                                } catch (Exception e) {
                                    data_state = 0;
                                }
                                if (data_state == 0) {
                                    moneyMaxContent.setText(data_state + "");
                                    sharedPreferanceUtils.setAppData(data_state + "");
                                    moneyMinContent.setText("0");
                                    howmoneyNum.setText("0");
                                    moneyMinContent.setText("0");
                                } else if (data_state > 0) {
                                    moneyMaxContent.setText(data_state + "");
                                    moneyMinContent.setText("500");
                                    buttonMoneyAdd.setEnabled(true);
                                    buttonMoneyMinus.setEnabled(true);
                                } else if (data_state <= 500) {
//                                buttonMoneyAdd.setEnabled(false);
                                }
                            }
//                        updateSelected();
                        }
                    }
                    break;
                case CHECKNO:
                    ApplyCouponInfo couponInfo = (ApplyCouponInfo) msg.obj;
                    if (couponInfo != null) {
                        if (couponInfo.getData() != null) {
                            couponId = couponInfo.getData().getCouponId();
                            if (TextUtils.isEmpty(couponId)) {
                                checkCoupId = -1;
                                couponId = "";
                                coupon_urgent_tv.setTextColor(Color.parseColor("#ff535353"));
                                urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
                            } else {
                                checkCoupId = 0;//有优惠券,但默认不勾选
                                coupon_urgent_tv.setTextColor(Color.parseColor("#DA3C21"));
                                urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
                            }
                        } else {
                            couponId = "";
                            checkCoupId = -1;
                            coupon_urgent_tv.setTextColor(Color.parseColor("#ff535353"));
                            urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
                        }
                        if(couponInfo.getCode().equals(Constants.DEFAULT_ERRORTIME_CODE)){
                            showShortToast1(couponInfo.getMsg());
                        }
                        else if(couponInfo.getCode().equals(Constants.DEFAULT_ERROR_CODE)){
                            showShortToast1(couponInfo.getMsg());
                        }
                    } else {
                        couponId = "";
                        checkCoupId = -1;
                        coupon_urgent_tv.setTextColor(Color.parseColor("#ff535353"));
                        urgent_coupon_checkbox.setImageResource(R.drawable.loap_coupon_check_unselect);
                    }
                    break;
            }

        }
    };
}
